#!/usr/bin/python

from urllib import urlopen,urlencode
import json

class Translator():
  """Translate text string"""
  def __init__(self, langFrom='EN-US', langTo='ZH-CN', encoding = 'UTF-8'):
    
    self.langFrom = langFrom
    self.langTo = langTo
    self.encoding = encoding
  
  def translate(self,text):
    """Transalte"""
    text = text.encode(self.encoding)
    return self.dictCN_translate(text.lower())
  
  def dictCN_translate(self,text):
    params = urlencode({'q':text,'t':'sug','ut':'0','ulang':self.langTo,'tlang':self.langFrom})
    translateSvc = "http://dict.bing.com.cn/io.aspx?%s" % params
    resultString =  urlopen(translateSvc).read().decode(self.encoding)

    resultJSON = json.loads(resultString)
    acs = resultJSON["ACS"]["AC"]
    if isinstance(acs,list):
      for ac in acs:
        if ac["$"].lower() == "{#*%s*$}" % text:
          return ac["$I"]
    elif isinstance(acs,dict):
      if acs["$"].lower() == "{#*%s*$}" % text:
        return acs["$I"]
    return None

if __name__ == '__main__':
  t = Translator()
  print t.translate('nanjing')
